package com.micro.service.auth.server.config.handler;


import com.google.common.collect.Maps;
import com.micro.service.auth.server.config.oauth2.OauthService;
import com.micro.service.auth.server.model.OauthClientDetails;
import com.micro.service.auth.server.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;

import java.io.Serializable;
import java.util.Map;

/**
* @Description: 自定义
* @author lvxiucai
* @create 14:47 2018/1/23
* @last modify by [lvxiucai 14:47 2018/1/23 ]
* @return
*/
public class OauthUserApprovalHandler extends TokenStoreUserApprovalHandler {

    @Autowired
    private OauthService oauthService;

    public OauthUserApprovalHandler() {
    }


    @Override
    public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
        //第一次进来approvalParams为空，requestParameters里有approve标志的值
        Map<String,String> map  = authorizationRequest.getApprovalParameters();
        if(map != null && map.size() == 0){
            map = authorizationRequest.getRequestParameters();
        }
        Map<String,Serializable> userMap = Maps.newHashMap();
        if(userAuthentication != null && userAuthentication.getPrincipal() != null){
            userMap.put("user",(User)userAuthentication.getPrincipal());
        }
        authorizationRequest.setExtensions(userMap);

        //approve--自定义的参数字段,用以区分是否需要授权操作，true：不需要；false：需要
        String approved = map.get("approve")==null?null:map.get("approve").toString();
        if( StringUtils.isNotBlank(approved) && StringUtils.equals(approved,"false")){
            return false;
        }
        if (super.isApproved(authorizationRequest, userAuthentication)) {
            return true;
        }
        if (!userAuthentication.isAuthenticated()) {
            return false;
        }

        OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId());
        return clientDetails != null && clientDetails.trusted();

    }

    @Override
    public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication){
        Map<String,String> map = authorizationRequest.getRequestParameters();
        if(map != null && map.get("approve") != null && ("false").equals(map.get("approve").toString())){
            Map<String,String> stringMap = Maps.newHashMap();
            stringMap.putAll(map);
            stringMap.put("approve","true");
            authorizationRequest.setApprovalParameters(stringMap);
        }
        return authorizationRequest;
    }

    public void setOauthService(OauthService oauthService) {
        this.oauthService = oauthService;
    }
}
